<?php
class BuyOrderService {
	
	private $_status = array (0 => "等待审核", 1 => "审核通过", 2 => "制单通过", 3 => "财务确认", 4 => "工厂发货", - 1 => "关闭" );
	private $_num = 20;
	
	/**
	 * 
	 * @param int $uid
	 * @param array $cart  goods和total
	 */
	public function addOrder($uid, $cart, $remark) {
		//获取订单号
		$orderno = $this->getOrderSNO ();
		//获取产品
		$goods = $this->getGoods ();
		if (empty ( $goods ['goods'] )) {
			return array ('status' => false, 'message' => "购物车是空的" );
		
		}
		
		//添加订单
		$o = $this->add ( $uid, $goods, $orderno, $goods ['total'], $remark );
		if ($o < 1) {
			return array ('status' => false, 'message' => "添加订单失败" );
		
		}
		//注入财务信息
		$a = $this->addAccount ( $uid, $orderno );
		if ($a < 1) {
			return array ('status' => false, 'message' => "添加财务失败" );
		
		}
		//成功后清理cookie
		setcookie ( "buy", "", - 86400, "/" );
		
		return array ('status' => true, 'message' => "恭喜你,订单提交成功" );
	}
	
	public function setStatusBySNO($status, $orderno, $user) {
		if (empty ( $orderno )) {
			return array ('status' => false, 'message' => "参数不正确" );
		}
		
		$flag = BuyOrderModel::instance ()->setOrderStatusBySNO ( $status, $orderno );
		
		if ($flag < 1) {
			$rs = array ('status' => false, 'message' => "更改状态失败" );
		} else {
			$rs = array ('status' => true, 'message' => "更改状态成功" );
		}
		
		//修改产品数量
		if ($status == 1 && $flag > 0) {
			$this->setGoodsSales ( $orderno );
		}
		$order = $this->getOrderBySNO ( $orderno );
		//增加操作记录
		$this->addLog ( $order ['id'], $user ['real_name'], $this->_status [$status] );
		//修改财务列表
		$status = $status < 2 ? $status : 1;
		$f = $this->setFinanceStatus ( $status, $orderno );
		
		return $rs;
	
	}
	
	public function setOrderByOrderSNO($v, $ordersno) {
		return BuyOrderModel::instance ()->setOrderByOrderSNO ( $v, $ordersno );
	}
	
	public function setOrderRemark($remark, $orderno) {
		$rs = BuyOrderModel::instance ()->setOrderRemark ( $remark, $orderno );
		if ($rs > 0) {
			$rs = array ('status' => true, 'message' => "备注成功" );
		} else {
			$rs = array ('status' => false, 'message' => "备注失败" );
		}
		return $rs;
	}
	
	//订单导出
	public function export($id) {
		
		if ($id < 0) {
			echo "参数不正确";
			exit ();
		}
		
		$this->setCSVHeader ();
		$rs = BuyOrderModel::instance ()->getOrderGreaterThanId ( $id, 1 );
		
		$format = "%s,%s,%s,%s,%s,%s,%s,%s\n";
		echo "序号,流水号,下单时间,订单名称,收货人,数量,总金额,状态\n";
		$member = new MemberService ();
		$i = 1;
		foreach ( $rs as $v ) {
			$money += $v ['money'];
			$user = $member->getMemberByUid ( $v ['uid'] );
			echo sprintf ( $format, $i, $v ['id'], date ( "Y-m-d H:i", $v ['add_time'] ), $v ['name'], $user ['real_name'], $v ['num'], $v ['money'], $this->_status [$v ['status']] );
			$i ++;
		}
		echo ",,,,,,$money,";
	}
	
	public function getOrderGreaterThanId($id, $status) {
		$rs = BuyOrderModel::instance ()->getOrderGreaterThanId ( $id, $status );
		return $this->parseOrder ( $rs );
	}
	
	public function stat() {
		$rs = BuyOrderModel::instance ()->getOrderByDate ();
		$num = count ( $rs ) - 1;
		$arr = array ();
		foreach ( $rs as $k => $v ) {
			$arr [$k] = $rs [$num - $k];
		}
		
		return $arr;
	}
	
	public function getOrderBySNO($sno) {
		return BuyOrderModel::instance ()->getOrderBySNO ( $sno );
	}
	
	public function getOrderById($id) {
		return BuyOrderModel::instance ()->getOrderById ( $id );
	}
	
	//根据订单状态获取订单
	public function getOrderByStatus($status) {
		return BuyOrderModel::instance ()->getOrderByStatus ( 0, 10, $status );
	}
	
	//订单明细
	public function getOrderByUid($pageid, $uid) {
		$total = BuyOrderModel::instance ()->countOrderByUid ( $uid );
		$page = $this->page ( $total, $pageid, $this->_num );
		$rs = BuyOrderModel::instance ()->getOrderByUid ( $page ['start'], $this->_num, $uid );
		
		$order = $this->parseOrder ( $rs );
		
		return array ('order' => $order, 'page' => $page, 'status' => $this->_status );
	}
	
	public function search($key, $value) {
		$value = urldecode ( $value );
		
		if ($key == "shr") {
			$member = new MemberService ();
			$user = $member->getMemberByWhere ( array ('real_name' => $value ) );
			$value = $user ['uid'];
			$key = 'uid';
		}
		$where = array ($key => $value );
		$rs = BuyOrderModel::instance ()->getOrderByWhere ( $where, 20 );
		$page = $this->page ( count ( $rs ), 1, $this->_num );
		
		$rs = $this->parseOrder ( $rs );
		return array ('order' => $rs, 'page' => $page, 'status' => $this->_status );
	
	}
	
	public function getOrder($pageid, $status) {
		if ($status === null) {
			$status = "all";
		}
		
		$total = BuyOrderModel::instance ()->countOrderByStatus ( $status );
		$page = $this->page ( $total, $pageid, $this->_num );
		$rs = BuyOrderModel::instance ()->getOrderPage ( $page ['start'], $this->_num, array ('status' => $status ) );
		$rs = $this->parseOrder ( $rs );
		
		$maxid = $rs [0] ['id'];
		return array ('order' => $rs, 's' => $status, 'maxid' => $maxid, 'page' => $page, 'status' => $this->_status );
	}
	
	public function merge($ids, $user) {
		
		if (empty ( $ids )) {
			return array ('status' => false, 'message' => "合并失败,请选择至少2个订单" );
		}
		$i = 0;
		
		if (! $this->checkOrderMerge ( $ids )) {
			return array ('status' => false, 'message' => "合并失败,订单状态不是等待审核或订单关闭或收货人不一致" );
		}
		$removeSno = array ();
		$orderinfo = new BuyOrderInfoService ();
		foreach ( $ids as $v ) {
			$order = BuyOrderModel::instance ()->getOrderById ( $v );
			$money += $order ['money'];
			$num += $order ['num'];
			if ($i == 0) {
				$id = $order ['id'];
				$newsno = $order ['orderno'];
			} else {
				array_push ( $removeSno, $order ['orderno'] );
				BuyOrderModel::instance ()->delOrderById ( $v );
				$orderinfo->setOrderInfoSNOBySNO ( $newsno, $order ['orderno'] );
			}
			$i ++;
		}
		
		$rs = $this->removeFinanceById ( $removeSno, $money, $newsno );
		
		if (! $rs ['status']) {
			return $rs;
		}
		$this->addLog ( $id, $user ['real_name'], "合并订单" );
		//更新总金额
		BuyOrderModel::instance ()->setOrderById ( array ('money' => $money, 'num' => $num ), $id );
		//删除多余的财务订单
		$data = array ('id' => $id, 'money' => $money, 'num' => $num );
		return array ('status' => true, 'data' => $data, 'message' => "订单合并成功" );
	}
	
	private function addLog($orderid, $username, $event) {
		$log = new BuyLogService ();
		$log->addLog ( $orderid, $username, $event );
	}
	
	private function addAccount($uid, $orderno) {
		$member = new MemberService ();
		$order = BuyOrderModel::instance ()->getOrderBySNO ( $orderno );
		$user = $member->getMemberByUid ( $uid );
		$account = new BuyAccountService ();
		$order ['payment'] = 1;
		$order ['remark'] = $order ['name'];
		$order ['chargetypes'] = 1;
		$order ['money'] = - $order ['money'];
		return $account->addAccount ( $user, $order, 0 );
	}
	
	/**
	 * 处理订单状态 和收货人
	 * @param unknown_type $rs
	 */
	private function parseOrder($rs) {
		$member = new MemberService ();
		$ls = new BuyLogService ();
		foreach ( $rs as $k => $v ) {
			$user = $member->getMemberByUid ( $v ['uid'] );
			$log = $ls->getLogByOrderId ( $v ['id'] );
			$rs [$k] ['action_name'] = $log [0] ['username'];
			$rs [$k] ['real_name'] = $user ['real_name'];
			$rs [$k] ['status'] = $this->_status [$v ['status']];
		}
		return $rs;
	}
	
	/**
	 * 删除合并后的财务明细
	 * @param array $snoArr
	 * @param decial $money
	 * @param string $orderno
	 */
	private function removeFinanceById($snoArr, $money, $orderno) {
		$finance = new BuyAccountService ();
		foreach ( $snoArr as $v ) {
			$s = $finance->removeAccountBySNO ( $v );
			if ($s < 1) {
				return array ('status' => false, 'message' => "删除财务失败" );
			}
		}
		$finance->setAccountMoneyBySNO ( - $money, $orderno );
		return array ('status' => true );
	}
	
	/**
	 * 合并订单
	 * 检查订单状态  订单所有人
	 */
	private function checkOrderMerge($ids) {
		$flag = true;
		$shr = array ();
		$i = 0;
		foreach ( $ids as $v ) {
			$order = BuyOrderModel::instance ()->getOrderById ( $v );
			
			if (empty ( $order )) {
				$flag = false;
				break;
			}
			
			if ($order ['status'] != 0) {
				$flag = false;
				break;
			}
			
			if (! in_array ( $order ['uid'], $shr ) && $i > 0) {
				$flag = false;
				break;
			}
			
			array_push ( $shr, $order ['uid'] );
			$i ++;
		}
		
		return $flag;
	}
	
	private function getGoods() {
		$buy = new BuyService ();
		return $buy->getCart ();
	
	}
	
	/**
	 * 
	 * 添加订单
	 * @param int $uid  收货人id
	 * @param array $goods 购物车明细
	 * @param string $orderno 订单号
	 * @param decimal $money 订单总额
	 * @param string remark 订单备注
	 */
	private function add($uid, $goods, $orderno, $money, $remark) {
		$params = array ('uid' => $uid, 'action_time' => time (), 'remark' => $remark, 'num' => $goods ['count'], 'name' => $goods ['goods'] [0] ['goods_name'], 'orderno' => $orderno, 'money' => $money, 'add_time' => time (), 'status' => 0 );
		
		$rs = BuyOrderModel::instance ()->addBase ( $params );
		$gService = new BuyOrderInfoService ();
		foreach ( $goods ['goods'] as $v ) {
			$cart = array ('sku' => $v ['sku'], 'snapshot' => $v ['snapshot'], 'goods_name' => $v ['goods_name'], 'orderno' => $orderno, 'goods_id' => $v ['id'], 'price' => $v ['price'], 'num' => $v ['count'], 'total_money' => $v ['price'] * $v ['num'] * $v ['count'] );
			$gService->add ( $cart );
			$cart = null;
		}
		
		return $rs;
	}
	
	private function getOrderSNO() {
		$sno = date ( "ymdHis", time () );
		$string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$prefix = '';
		for($i = 0; $i < 4; $i ++) {
			$rand = rand ( 0, 33 );
			$prefix .= $string {$rand};
		}
		$sno = $sno . $prefix;
		return $sno;
	}
	
	private function setFinanceStatus($status, $orderno) {
		$account = new BuyAccountService ();
		return $account->setAccountBySNO ( $status, $orderno );
	}
	
	/**
	 * 
	 * 更改产品销售数量
	 * @param string $sno
	 * @param int $type
	 */
	private function setGoodsSales($orderno) {
		$goods = new BuyService ();
		$orderinfo = new BuyOrderInfoService ();
		$goodsArr = $orderinfo->getGoodsBySNO ( $orderno );
		foreach ( $goodsArr as $v ) {
			
			$rs = $goods->getGoodsById ( $v ['goods_id'] ); //获取产品信息
			$num = $rs ['sales'] + $v ['num'];
			$goods->setGoodsSalesById ( $num, $v ['goods_id'] ); //更新产品销量
			$num = 0;
		}
	
	}
	
	/**
	 * 分页
	 *
	 * @return void
	 */
	private function page($total, $pageid, $num) {
		$pageid = isset ( $pageid ) ? $pageid : 1;
		
		$start = ($pageid - 1) * $num;
		$pagenum = ceil ( $total / $num );
		/*修正分类不包含内容 显示404错误*/
		$pagenum = $pagenum == 0 ? 1 : $pagenum;
		/*如果超过了分类页数 404错误*/
		
		if ($pageid > $pagenum) {
			return false;
		}
		
		return array ('start' => $start, 'num' => $num, 'current' => $pageid, 'page' => $pagenum );
	}
	
	private function setCSVHeader() {
		header ( "Cache-Control: public" );
		header ( "Pragma: public" );
		header ( "Content-type:application/vnd.ms-excel" );
		$file = "来自订购系统" . date ( "md", time () );
		header ( "Content-Disposition:attachment;filename=$file.csv" );
	}

}